﻿using System.Collections.Generic;
using System.Threading.Tasks;
using IdentityServer4.Models;
using K9Nano.Share.Exceptions;
using Microsoft.AspNetCore.Mvc;

namespace K9Nano.Admin.Identity
{
    [ApiController]
    [Route("Client/[Action]")]
    public class ClientController : ControllerBase
    {
        protected readonly IClientAppService Service;

        public ClientController(IClientAppService service)
        {
            Service = service;
        }

        [HttpGet]
        public async Task<IReadOnlyList<Client>> GetAll()
        {
            return await Service.GetAllAsync(HttpContext.RequestAborted);
        }

        [HttpGet]
        public async Task<Client> Get(string clientId)
        {
            return await Service.FindClientByIdAsync(clientId, HttpContext.RequestAborted);
        }

        [HttpPost]
        public async Task Create([FromBody] Client scope)
        {
            if (string.IsNullOrEmpty(scope.ClientId))
            {
                throw new K9UserFriendlyException("Client ID 不能为空");
            }

            if (scope.ClientSecrets.Count == 0)
            {
                throw new K9UserFriendlyException("ClientSecrets 不能为空");
            }

            await Service.CreateAsync(scope, HttpContext.RequestAborted);
        }

        [HttpDelete]
        public async Task Delete(string clientId)
        {
            if (string.IsNullOrEmpty(clientId))
            {
                throw new K9UserFriendlyException("clientId 不能为空");
            }

            await Service.DeleteAsync(clientId, HttpContext.RequestAborted);
        }

        [HttpPost]
        public async Task SetEnable(string clientId, bool enable)
        {
            if (string.IsNullOrEmpty(clientId))
            {
                throw new K9UserFriendlyException("clientId 不能为空");
            }

            await Service.SetEnableAsync(clientId, enable, HttpContext.RequestAborted);
        }
    }
}